package com.zkingsoft.services.pc.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zkingsoft.dao.bus.BusParameterSettingsDao;
import com.zkingsoft.dao.pc.PcFoodMaterialDao;
import com.zkingsoft.dao.pc.PcMealSettingsDao;
import com.zkingsoft.dao.pc.PcMenuDetailDao;
import com.zkingsoft.dao.pc.PcMenuFoodDao;
import com.zkingsoft.dao.pc.PcMenuManageDao;
import com.zkingsoft.dao.pc.PcMenuRecordDao;
import com.zkingsoft.dao.pc.PcMicroElementDao;
import com.zkingsoft.dao.pc.PcMicroFoodDao;
import com.zkingsoft.exception.GlobleException;
import com.zkingsoft.model.bus.BusParameterSettings;
import com.zkingsoft.model.pc.Elements;
import com.zkingsoft.model.pc.Foods;
import com.zkingsoft.model.pc.HelpMenuDetail;
import com.zkingsoft.model.pc.MenuFoods;
import com.zkingsoft.model.pc.PcFoodMaterial;
import com.zkingsoft.model.pc.PcMealSettings;
import com.zkingsoft.model.pc.PcMenuDetail;
import com.zkingsoft.model.pc.PcMenuFood;
import com.zkingsoft.model.pc.PcMenuManage;
import com.zkingsoft.model.pc.PcMenuRecord;
import com.zkingsoft.model.pc.PcMicroElement;
import com.zkingsoft.model.pc.PcMicroFood;
import com.zkingsoft.pojo.PaginationVO;
import com.zkingsoft.services.pc.PcMenuDetailService;
import com.zkingsoft.util.DateUtils;
import com.zkingsoft.util.ModelUtils;

/**
 * This field was generated by Zking.software.Codegen.
 * 
 * @date 2017-03-24 11:05
 */
@Service("pcMenuDetailService")
public class PcMenuDetailServiceImpl implements PcMenuDetailService {
	Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private PcMealSettingsDao pcMealSettingsDao;  //配餐设置
	@Autowired
	private PcMenuDetailDao pcMenuDetailDao; //菜谱明细
	@Autowired
	private PcMenuManageDao pcMenuManageDao; //菜谱管理
	@Autowired
	private PcMenuFoodDao pcMenuFoodDao; //菜谱与原材料关系
	@Autowired
	private PcFoodMaterialDao pcFoodMaterialDao; //原材料
	@Autowired
	private PcMenuRecordDao pcMenuRecordDao; // 菜单记录表Dao
	@Autowired
	private PcMicroElementDao pcMicroElementDao; // 微量元素表Dao
	@Autowired
	private PcMicroFoodDao pcMicroFoodDao; // 微量元素与原材料中间表Dao
	@Autowired
	private BusParameterSettingsDao busParameterSettingsDao; // 参数设置
	/**
	 *  @Description 菜谱修改时更新原材料
		@author :heming
		@date2017年3月28日
	 */
	@Override
	public int updateMaterial(PcMenuManage pcMenuManage){
		List<PcMenuManage> menuList = pcMenuManage.getMenuManages();
		BusParameterSettings bus=new BusParameterSettings();
		bus.setParamCode("rs");
		List<BusParameterSettings> busList=busParameterSettingsDao.selectByModel(bus);
		Long rs=null;
		for(BusParameterSettings b:busList){
			rs=Long.parseLong(b.getParamValue());
		}
		PcMenuDetail pcMenuDetail=findMaterial(menuList,rs);
		return pcMenuDetailDao.updateByModel(pcMenuDetail);
	}
	/**
	 *  @Description 根据菜谱集合找到对应的原材料用量
		@author :heming
		@date2017年3月28日
	 */
	public PcMenuDetail findMaterial(List<PcMenuManage> menuList,Long rs){
		PcMenuDetail pcMenuDetail=new PcMenuDetail();
		String foodIds=null;
		Long id=null;
		if(menuList != null){
			int i=0;
			String materialIds="";
			List<PcFoodMaterial> mlist=new ArrayList<PcFoodMaterial>();
			for(PcMenuManage m:menuList){
				i++;
				if(m != null && m.getMenId()!= null ){
					PcMenuFood pcMenuFood=new PcMenuFood();
					pcMenuFood.setMenId(m.getMenId());
					List<PcMenuFood> menuFoodList=pcMenuFoodDao.selectByModel(pcMenuFood);
					for(PcMenuFood menuFood:menuFoodList){
						if(menuFood!=null && menuFood.getFodId()!=null){
							Long fodId=menuFood.getFodId();
							Integer menSingle=menuFood.getMenSingle();
							BigDecimal b=new BigDecimal(menSingle);
							if(menuFood.getMenUnit() != null && menuFood.getMenUnit().equals("千克")){
								b=new BigDecimal(1000).multiply(b);//单位换算
							}
							BigDecimal t=new BigDecimal(rs).multiply(b);//乘以用餐人数
							Long total=t.longValue();
							PcFoodMaterial mater=new PcFoodMaterial();
						    mater.setFodId(fodId);
						    mater.setWeight(total.toString());
							if(i==1){
							    mlist.add(mater);
							}else{
								boolean f=false;
								for(PcFoodMaterial mat:mlist){
									if(mat.getFodId()==fodId){
										f=true;
										total+=Long.valueOf(mat.getWeight());
										mat.setWeight(total.toString());
									}
								}
								if(!f)
									mlist.add(mater);
							}
						    
						}
						
				}
				
				if(i>1){
					foodIds += ","+m.getMenId();
				}else{
					foodIds = m.getMenId().toString();
				}
				}
				if( m.getDetailMenId()!= null && id==null){
					id=m.getDetailMenId();
				}
			}
			for(int y=0;y<mlist.size();y++){
				if(y==0){
					materialIds=mlist.get(y).getFodId()+":"+mlist.get(y).getWeight();
				}else{
					materialIds+=","+mlist.get(y).getFodId()+":"+mlist.get(y).getWeight();
				}
			}
			
			if(id != null){
				pcMenuDetail=pcMenuDetailDao.selectById(id);
			}
			pcMenuDetail.setMaterialIds(materialIds);
			pcMenuDetail.setFoodIds(foodIds);
			}
			return pcMenuDetail;
	}

	@Override
	public int batchAdd(List<PcMenuDetail> pcMenuDetailList) {
		int num = 0;

		int c = 10000;
		int size = pcMenuDetailList.size() / c + 1;
		for (int i = 0; i < size; i++) {
			int begin = i * c;
			int end = (i + 1) * c;
			end = end >= pcMenuDetailList.size() ? pcMenuDetailList.size()
					: end;
			List<PcMenuDetail> insertList = pcMenuDetailList
					.subList(begin, end);
			num += pcMenuDetailDao.batchInsert(insertList);
		}
		return num;

	}

	@Override
	public int modifyByMap(PcMenuDetail oldPcMenuDetail,PcMenuDetail newPcMenuDetail) {

		if (!ModelUtils.isModified(oldPcMenuDetail, newPcMenuDetail)) {
			return 1;
		}
		Map<String, Object> modifyMap = null;
		try {
			modifyMap = ModelUtils.comparePojo2Map(oldPcMenuDetail,
					newPcMenuDetail);
		} catch (Exception e) {
			throw new GlobleException("数据对比失败");
		}
		if (modifyMap.size() > 0) {
			modifyMap.put("menId", oldPcMenuDetail.getMenId());
			pcMenuDetailDao.updateByMap(modifyMap);
		}
		return 1;
	}

	@Override
	public int modifyByModel(PcMenuDetail pcMenuDetail) {
		return pcMenuDetailDao.updateByModel(pcMenuDetail);

	}

	@Override
	public int remove(List<Long> list) {

		return pcMenuDetailDao.deleteByIds(list);

	}

	@Override
	public int removeById(Long menId) {

		return pcMenuDetailDao.deleteById(menId);

	}

	@Override
	public int removeByModel(PcMenuDetail pcMenuDetail) {

		return pcMenuDetailDao.deleteByModel(pcMenuDetail);

	}

	@Override
	public List<PcMenuDetail> findInPage(PcMenuDetail pcMenuDetail,
			PaginationVO pageVo) {

		return pcMenuDetailDao.selectInPage(pcMenuDetail, pageVo);

	}

	@Override
	public List<PcMenuDetail> findByModel(PcMenuDetail pcMenuDetail) {

		return pcMenuDetailDao.selectByModel(pcMenuDetail);

	}

	@Override
	public int findTotal(PcMenuDetail pcMenuDetail) {

		return pcMenuDetailDao.selectTotalRecord(pcMenuDetail);

	}

	@Override
	public PcMenuDetail findById(Long menId) {
		
		return pcMenuDetailDao.selectById(menId);

	}
	/**
	 *  @Description 查询一周菜谱数据
	 *  先查询出pcMenuDetail表对应的mrId所有数据
	 *  
		@author :heqiuyun
		@date2017年3月29日
	 */
	@Override
	public List<HelpMenuDetail> findFoods(PcMenuRecord pcMenuRecord,boolean f) {
			List<HelpMenuDetail> helpList = new ArrayList<HelpMenuDetail>();
			PcMenuDetail pcMenuDetail =new PcMenuDetail();
			pcMenuDetail.setMrId(pcMenuRecord.getMenId());
			//查询出所有mrId==pcMenuRecord的men_id数据
			List<PcMenuDetail> menuDetailList=pcMenuDetailDao.selectByModel(pcMenuDetail);
			int i=0;
			HelpMenuDetail help=null;
			List<Foods> foodsList=null;
			String meal="";
			for(PcMenuDetail menuDetail:menuDetailList){
				if(i==0){//星期一
					help=new HelpMenuDetail();
					foodsList = new ArrayList<Foods>();
					meal=menuDetail.getMenMeal();//餐期
				}	
					Long detailMenId=menuDetail.getMenId();
					String foodIds=menuDetail.getFoodIds();
					String materilIds=menuDetail.getMaterialIds();
					Foods foods=new Foods();
					List<PcFoodMaterial> materialList=new ArrayList<PcFoodMaterial>();
					if(foodIds!=null){
					
					String[] arrFoodIds=foodIds.split(",");
					List<Long> ids=new ArrayList<Long>();
					for(String str:arrFoodIds){
						if(str!=null && str!="" && str!="null" && isInteger(str)){
							ids.add(Long.parseLong(str));
						}
						
					}
					List<PcMenuManage> foodList=pcMenuManageDao.selectByIds(ids);
					foods.setFood(foodList);
					for(PcMenuManage menuMange:foodList){
						menuMange.setDetailMenId(detailMenId);
					}
					ids=new ArrayList<Long>();
					List<BigDecimal> weights=new ArrayList<BigDecimal>();
					String[] arrMaterilIds=materilIds.split(",");
					//
					for(String str:arrMaterilIds){
						String[] arr = str.split(":");
						if(arr[0]!=null && !"".equals(arr[0]) && isInteger(arr[0])){
							ids.add(Long.parseLong(arr[0]));
							BigDecimal weight=new BigDecimal(arr[1]);
							if(f){//是否需要转千克
								weight=weight.divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP);
							}
							weights.add(weight);
						}
					}
					
					if(ids!=null && ids.size()>0){
						materialList=pcFoodMaterialDao.selectByIds(ids);
						
						for(PcFoodMaterial foodMaterial:materialList){
							int index=0;
							int x=0;
							for(Long id:ids){
								if(foodMaterial.getFodId().equals(id)){
									index=x;
									continue;
								}
								x++;
							}
								foodMaterial.setWeight(weights.get(index).toString());
								foodMaterial.setDetailMenId(detailMenId);
								
								}
					}
					}
					//
					foods.setMaterial(materialList);
					foodsList.add(foods);
				i++;
				if(i==5)//星期五
				{
					i=0;
					help.setMeal(meal);
					help.setFoods(foodsList);
					helpList.add(help);
				}
			}
			return helpList;
		}
	@Override
	public int add(PcMenuDetail obje) {
		return 0;
	}

	/**
	 *  @Description 生成一周菜谱数据存入PcMenuDetail表
		@author :heming
		@date2017年3月26日
	 */
	@Override
	public int addDetail(PcMenuRecord pcMenuRecord) {
		Long mrId=pcMenuRecord.getMenId();
		Date WeekTime=pcMenuRecord.getMenBeginTime();//得到谱记录表开始时间
		// 得到餐配中的对象
		List<PcMealSettings> mealList = pcMealSettingsDao.selectByModel(null);
		int m=0,j=0;
		List<String> mealArr=new ArrayList<String>();
		List<List<PcMenuManage>> list1=new ArrayList<List<PcMenuManage>> ();
		BusParameterSettings bus=new BusParameterSettings();
		bus.setParamCode("rs");
		List<BusParameterSettings> busList=busParameterSettingsDao.selectByModel(bus);
		Long rs=null;
		for(BusParameterSettings b:busList){
			rs=Long.parseLong(b.getParamValue());
		}
		
		List<List<PcMenuDetail>> l=new ArrayList<List<PcMenuDetail>>();
		for (PcMealSettings pcMealSettings : mealList) {
			//是否同餐期有多个种类
			boolean repeat=false;
			List<PcMenuDetail> datailList=new ArrayList<PcMenuDetail>();
			if(pcMealSettings.getMesMeal()!=null){
				String meal=pcMealSettings.getMesMeal();
				
				if(mealArr.contains(meal)){
					repeat=true;
				}else{
					mealArr.add(meal);
				}
				Long amount=pcMealSettings.getMesAmount();
				PcMenuManage menuManage= new PcMenuManage();
				menuManage.setMenType(pcMealSettings.getMesMeuId());
				List<PcMenuManage> menuManageList=pcMenuManageDao.selectByModel(menuManage);
				
					Random ran=new Random();
					//星期一到星期五，五次循环开始
					for(int i=0 ; i<5 ; i++){
						//生成菜
						List<PcMenuManage> list2=new ArrayList<PcMenuManage>();
						if(menuManageList != null && menuManageList.size()>0){
						for(int n =0 ; n<amount ;n++){
							//控制while循环退出条件
							boolean f=true;
							//循环次数
							int count=0;
							while(f){
								count++;
								int x=ran.nextInt(menuManageList.size());
								//循环十次，如无达标，则不再随机
								if(count>3){
									f=false;
									list2.add(menuManageList.get(x));
								}
								if(j==0){
									if(i==0){
										//星期一第一餐，检测同餐是否有重复
										if(!list2.contains(menuManageList.get(x))){
											f=false;
											list2.add(menuManageList.get(x));
										}
									}else{
										//同餐期，检测相邻是否有重复
										if(!list2.contains(menuManageList.get(x)) 
												&& !list1.get(i-1).contains(menuManageList.get(x))
												){
											f=false;
											list2.add(menuManageList.get(x));
										}
									}
									
								}else{
									//检测相邻餐期、相邻日期菜是否有重复，
									if(!list2.contains(menuManageList.get(x)) 
											&& !list1.get((j*5+i)-5).contains(menuManageList.get(x))
											&& !list1.get(j*5+i-1).contains(menuManageList.get(x))){
										f=false;
										list2.add(menuManageList.get(x));
									}
								}
							}
						}
						list1.add(list2);
						PcMenuDetail pcMenuDetail =findMaterial(list2,rs);;
						pcMenuDetail.setMrId(mrId);
						pcMenuDetail.setMenMeal(meal);
						pcMenuDetail.setMenTime(new Date(WeekTime.getTime()+(i+1) * 24 * 60 * 60 * 1000));
						datailList.add(pcMenuDetail);
						}else{
							list1.add(list2);
							PcMenuDetail pcMenuDetail =new PcMenuDetail();;
							pcMenuDetail.setMrId(mrId);
							pcMenuDetail.setMenMeal(meal);
							pcMenuDetail.setMenTime(new Date(WeekTime.getTime()+(i+1) * 24 * 60 * 60 * 1000));
							datailList.add(pcMenuDetail);
						}
						
						
					}//星期一到星期五，五次循环结束
					if(repeat==false){
						j++;
					}else{
						//更新相同餐期的集合对象
						for(int y=0 ; y<l.size() ;y++){
							List<PcMenuDetail> p = l.get(y);
							if(p.size()>0){
							if(p.get(p.size()-1)
									.getMenMeal()
									.equals(datailList
											.get(datailList.size()-1)
											.getMenMeal())){
								for(int z=0 ; z<p.size() ;z++){
									if(p.get(z).getFoodIds()==null){
										p.get(z).setFoodIds(datailList.get(z).getFoodIds());
									}else{
										p.get(z).setFoodIds(p.get(z).getFoodIds()+","+datailList.get(z).getFoodIds());
									}
									if(p.get(z).getMaterialIds()==null){
									p.get(z).setMaterialIds(datailList.get(z).getMaterialIds());
									}else{
										p.get(z).setMaterialIds(p.get(z).getMaterialIds()+","+datailList.get(z).getMaterialIds());
									}
									}

								
							}
							}
							
						}
					}
				
				if(repeat==false){
					l.add(datailList);
				}
			}//if
		}//for
		for(int y=0 ; y<l.size() ;y++){
			List<PcMenuDetail> p = l.get(y);
			for(int z=0 ; z<p.size() ;z++){
				//合并重复的材料用量
				m+=pcMenuDetailDao.insert(combine(p.get(z)));
			}
		}
		Long end=System.currentTimeMillis();
		return m;
	}
	/**
	 * 合并重复的原材料用量
	 */
	public PcMenuDetail  combine(PcMenuDetail pcMenuDetail){
		String s=pcMenuDetail.getMaterialIds();
		String materialIds="";
		int i=0;
		List<PcFoodMaterial> mlist=new ArrayList<PcFoodMaterial>();
		if(s!=null && s.contains(":")){
			String[] arr1=s.split(",");
			for(String str:arr1){
				i++;
				String[] arr2=str.split(":");
				if(arr2[0]!=null && !"null".equals(arr2[0])){//出错
				Long fodId=Long.parseLong(arr2[0]);
				Long total=Long.parseLong(arr2[1]);
				PcFoodMaterial mater=new PcFoodMaterial();
			    mater.setFodId(fodId);
			    mater.setWeight(total.toString());
				if(i==1){
				    mlist.add(mater);
				}else{
					boolean f=false;
					for(PcFoodMaterial mat:mlist){
						if(mat.getFodId()==fodId){
							f=true;
							total+=Long.valueOf(mat.getWeight());
							mat.setWeight(total.toString());
						}
					}
					if(!f)
						mlist.add(mater);
				}
			    
			}
				}
		}
		
		for(int y=0;y<mlist.size();y++){
			if(y==0){
				materialIds=mlist.get(y).getFodId()+":"+mlist.get(y).getWeight();
			}else{
				materialIds+=","+mlist.get(y).getFodId()+":"+mlist.get(y).getWeight();
			}
		}
		pcMenuDetail.setMaterialIds(materialIds);
		return pcMenuDetail;
	}
	/* 
	  * 判断是否为整数  
	  * @param str 传入的字符串  
	  * @return 是整数返回true,否则返回false  
	*/  
	  
	  
	  public static boolean isInteger(String str) {    
	    Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");    
	    return pattern.matcher(str).matches();    
	  }  
	  
	  /**
		 * 生成微量元素表(营养供给量)
		 */
		
	   	public List<Elements> findElements(PcMenuRecord pcMenuRecord,List<HelpMenuDetail> helpList){
			//List<HelpMenuDetail> helpList = findFoods(pcMenuRecord,false);
			Long rs=pcMenuRecord.getMenManMun();
			String[] strDate={"星期一","星期二","星期三","星期四","星期五"};
			List<Elements> elementsList=new ArrayList<Elements>();
			for(int i = 0 ; i< strDate.length ; i++){//星期几
				List<PcMicroElement> eleList=pcMicroElementDao.selectByModel(null);
				Elements elements=new Elements();
				elements.setTime(strDate[i]);
				Map<Long,BigDecimal> elementMap=new HashMap<Long,BigDecimal>();
				Map<Long,BigDecimal> map=new HashMap<Long,BigDecimal>();
				BigDecimal energy=new BigDecimal(0);
					for(int j = 0 ; j< helpList.size() ; j++){//餐期
						HelpMenuDetail h=(HelpMenuDetail) helpList.get(j);
						Foods foods=h.getFoods().get(i);
						 List<PcFoodMaterial> material=foods.getMaterial();
						 if(material!=null){
						 for(PcFoodMaterial ma:material){
							 if(ma.getWeight()!=null){
								 BigDecimal b=new BigDecimal(ma.getWeight());
								 b=new BigDecimal(1000).multiply(b);//乘
								 if(map.containsKey(ma.getFodId())){
									 BigDecimal total=map.get(ma.getFodId());
									 total=total.add(b);
									 map.put(ma.getFodId(), total);
								 }else{
									 map.put(ma.getFodId(), b);
								 } 
							 }
							
						 }
					}
					}//餐期
					Set<Long> set=map.keySet();
					Iterator<Long> it=set.iterator();
					while(it.hasNext()){//每个原材料
						Long fodId=it.next();
						BigDecimal total=map.get(fodId);
						total=total.divide(new BigDecimal(rs), 4, RoundingMode.HALF_UP);
						PcFoodMaterial pcFoodMaterial=pcFoodMaterialDao.selectById(fodId);//原材料
						Integer fodPart= pcFoodMaterial.getFodPart();//食部
						List<PcMicroFood> microFoodList=pcMicroFoodDao.selectFoodMaterial(fodId);//微量元素
						BigDecimal b=new BigDecimal(pcFoodMaterial.getFodEnergy()).multiply(total);
						b=new BigDecimal(fodPart).multiply(b);
						b=b.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);//除
						
						//b=b.divide(new BigDecimal(1), 2, RoundingMode.HALF_UP);
						energy=energy.add(b);
						
						BigDecimal totalAmount=null;
						//每个原材料对应的微量元素表集合
						for(PcMicroFood mf:microFoodList){
							if(mf!=null && mf.getMicAmount()!=null && mf.getMicAmount()!=0){
							totalAmount=new BigDecimal(mf.getMicAmount()).multiply(total);//乘
							totalAmount=new BigDecimal(fodPart).multiply(totalAmount);
							totalAmount=totalAmount.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
							
							if(elementMap.containsKey(mf.getMicId())){
								totalAmount=totalAmount.add(elementMap.get(mf.getMicId()));
							}
							
							elementMap.put(mf.getMicId(), totalAmount);
							}
						}
						
					}
					//根据map集合数据更新eleList
					for(PcMicroElement me:eleList){
						if(elementMap.containsKey(me.getMicId())){
							if(me.getMicName().equals("脂肪")){
								BigDecimal b=new BigDecimal(900).multiply(elementMap.get(me.getMicId()));
								 b= b.divide(energy, 2, RoundingMode.HALF_UP);
								me.setMicAmount(b.doubleValue());
							}else{
								BigDecimal amount=elementMap.get(me.getMicId()).divide(new BigDecimal(1), 2, RoundingMode.HALF_UP);
								me.setMicAmount(amount.doubleValue());
							}
						}
					}
					energy=energy.divide(new BigDecimal(1), 2, RoundingMode.HALF_UP);
					
				elements.setEnergy(energy.doubleValue());
				elements.setMiceList(eleList);
				elementsList.add(elements);
			}//
			//添加最后一栏，标准量到集合
			List<PcMicroElement> eleList=pcMicroElementDao.selectByModel(null);
			Elements elements=new Elements();
			elements.setTime("标准量");
			List<PcMicroFood> microFoodList=pcMicroFoodDao.selectFoodMaterial(Long.valueOf(0));
			for(PcMicroElement me:eleList){
				for(PcMicroFood mf:microFoodList){
					if(mf.getMicId()==me.getMicId()){
						me.setMicAmount(mf.getMicAmount());
					}
				}
			}
			elements.setEnergy(1450.00);
			elements.setMiceList(eleList);
			elementsList.add(elements);
			return elementsList;
	   	}
		
	/**
	 * 查询一周菜谱数据生成Excel表单
	 */
	@Override
	public List< List< Object > > exportExcel(PcMenuRecord pcMenuRecord){
		List<HelpMenuDetail> dlist = findFoods(pcMenuRecord,true);
		List< MenuFoods > dataList = new ArrayList<MenuFoods >();
		for (HelpMenuDetail h:dlist){
			MenuFoods menuFoods=new MenuFoods();
			String meal=h.getMeal();
			List<String> fods=new ArrayList<String>();
			List<String> mas=new ArrayList<String>();
			List<Foods>  foods =h.getFoods();//包含星期一到星期五
			for(Foods f:foods){
				 List<PcMenuManage> food =f.getFood();
				 String fod="";
				 String ma="";
				 int n=0;
				for(PcMenuManage p:food){
					if(n==0)
						fod+=p.getMenName();
					else 
						fod+="\r\n"+p.getMenName();
				n++;
				}
				fods.add(fod);
				List<PcFoodMaterial> material=f.getMaterial();
				n=0;
				for(PcFoodMaterial m:material){
					if(n==0)
						ma+=m.getFodName()+":"+m.getWeight();
					else 
						ma+="\r\n"+m.getFodName()+":"+m.getWeight();
					n++;
				}
				mas.add(ma);
			}
			menuFoods.setMeal(meal);
			menuFoods.setFoods(fods);
			menuFoods.setMas(mas);
			dataList.add(menuFoods);
		}
		List< List< Object > > list=new ArrayList< >();
		for (MenuFoods obj : dataList) {
			List< Object >  temp = new ArrayList< >();
			temp.add(obj.getMeal());
			temp.add(obj.getFoods().get(0));
			temp.add(obj.getMas().get(0));
			temp.add(obj.getFoods().get(1));
			temp.add(obj.getMas().get(1));
			temp.add(obj.getFoods().get(2));
			temp.add(obj.getMas().get(2));
			temp.add(obj.getFoods().get(3));
			temp.add(obj.getMas().get(3));
			temp.add(obj.getFoods().get(4));
			temp.add(obj.getMas().get(4));
			list.add(temp);
			}
		return list;
	}
	/**
	 * 通用方法，根据集合数据创建Excel单格
	 */
	@Override
	public HSSFWorkbook generateExcel(String title,String strTitle, String[] headers,List<List<Object>> list,String name) {  
		HSSFWorkbook book = new HSSFWorkbook();  
        try{  
             HSSFSheet sheet = book.createSheet("Sheet1");  
            //样式设置  
            HSSFCellStyle style = book.createCellStyle();  
            style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);  
              style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
              style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
              style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
              // 生成一个字体  
              HSSFFont font = book.createFont();  
              font.setColor(HSSFColor.VIOLET.index);  
              font.setFontHeightInPoints((short) 12);  
              font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
              // 把字体应用到当前的样式  
              style.setFont(font);  
              HSSFCellStyle style2 = book.createCellStyle();  
                  //设置上下左右边框  
                  style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
                  style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
                  style2.setBorderRight(HSSFCellStyle.BORDER_THIN);  
                  style2.setBorderTop(HSSFCellStyle.BORDER_THIN);  
                  style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
                  style2.setWrapText(true); // 设置为自动换行  
                  style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
                   //设置单元格背景色
                style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
          		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
              //填充表头标题  
              int colSize = list.get(0).size();  
              //合并单元格供标题使用(表名)  
              sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, colSize-1));  
              HSSFRow firstRow = sheet.createRow(0);//第几行（从0开始）  
              firstRow.setHeight((short)(800));
              HSSFCell firstCell = firstRow.createCell(0);  
              firstCell.setCellValue(title);  
              firstCell.setCellStyle(style);  
              //合并单元格供第一个字符串使用  
              sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, colSize-1));  
              HSSFRow firstNextRow = sheet.createRow(1);//第几行（从0开始）  
              firstNextRow.setHeight((short)(500));
              HSSFCell firstNextCell = firstNextRow.createCell(0);  
              firstNextCell.setCellValue(strTitle);  
              firstNextCell.setCellStyle(style);  
              //填充表头header  
              HSSFRow row = sheet.createRow(2); 
              for(int i=0; i< headers.length; i++) {  
            	  sheet.autoSizeColumn((short)i,true);
                  HSSFCell cell = row.createCell(i);  
                  cell.setCellValue(headers[i]);  
                  cell.setCellStyle(style2);  
              }  
              //填充表格内容  
              int[] arr=new int[list.get(list.size()-1).size()];
              for(int i=0; i<list.size(); i++) { 
                  HSSFRow row2 = sheet.createRow(i+3);//index：第几行  
                  List<?> rowList = list.get(i);  
                  int x=1;
                  for(int j=0; j<rowList.size(); j++) {
                	 int y=1;
                	 int r=1;
                	  String textValue = "";  
                      Object value = rowList.get(j);  
                      HSSFCell cell = row2.createCell(j);//第几列：从0开始  
                      if (value instanceof Integer) {
  						cell.setCellValue((Integer) value);
  					} else if (value instanceof Float) {
  						textValue = String.valueOf((Float) value);
  						cell.setCellValue(textValue);
  					} else if (value instanceof Double) {
  						textValue = String.valueOf((Double) value);
  						cell.setCellValue(textValue);
  					} else if (value instanceof Long) {
  						cell.setCellValue((Long) value);
  					} else if (value instanceof Boolean) {
  						textValue = "是";
  						if (!(Boolean) value) {
  							textValue = "否";
  						}
  						cell.setCellValue(textValue);
  					}else {
  						// 其它数据类型都当作字符串简单处理
  						if (value != null) {
  							textValue = value.toString();
  						}
  						cell.setCellValue(textValue);
  					}
                      String[] str=textValue.split("\r\n");
                      for(int t= 0 ;t<str.length ;t++){
                    	  if(str[t].length()>r)
                    		  r=str[t].length();
                      }      
                      if(r>arr[j])
                    	  arr[j]=r;
                      cell.setCellStyle(style2); 
                      y=textValue.split("\r\n").length;
                     if(y>x)
                    	 x=y;
                  }  
                  row2.setHeight((short)(x*300));
              }  
              for(int h=0;h<arr.length;h++){
            	  if("菜谱".equals(name)){
            	  sheet.setColumnWidth(h, 580*arr[h]);
            	  }else{
            		  if(h>0){
            			  sheet.setColumnWidth(h, 300*arr[h]);
            		  }else{
            			  sheet.setColumnWidth(h, 550*arr[h]);
            		  }
            	  }
              }
              if("菜谱".equals(name)){
            	  sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 2));   
                  sheet.addMergedRegion(new CellRangeAddress(2, 2, 3, 4)); 
                  sheet.addMergedRegion(new CellRangeAddress(2, 2, 5, 6)); 
                  sheet.addMergedRegion(new CellRangeAddress(2, 2, 7, 8)); 
                  sheet.addMergedRegion(new CellRangeAddress(2, 2, 9, 10));
              }
               
        } catch(Exception ex) {  
            ex.printStackTrace();  
        }  
        return book;  
    } 
	/**
	 * 生成Excel多个表格
	 */
	@Override
	public HSSFWorkbook generateExcelTwo(String[] title,String strTitle, String[][] headers,List<List<List<Object>>> list,String name) {  
		HSSFWorkbook book = new HSSFWorkbook();  
        try{  
             HSSFSheet sheet = book.createSheet("Sheet1");  
            //样式设置  
            HSSFCellStyle style = book.createCellStyle();  
            style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);  
              style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
              style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
              style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
              // 生成一个字体  
              HSSFFont font = book.createFont();  
              font.setColor(HSSFColor.VIOLET.index);  
              font.setFontHeightInPoints((short) 12);  
              font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
              // 把字体应用到当前的样式  
              style.setFont(font);  
              HSSFCellStyle style2 = book.createCellStyle();  
                  //设置上下左右边框  
                  style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
                  style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
                  style2.setBorderRight(HSSFCellStyle.BORDER_THIN);  
                  style2.setBorderTop(HSSFCellStyle.BORDER_THIN);  
                  style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
                  style2.setWrapText(true); // 设置为自动换行  
                  style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
                   //设置单元格背景色
                style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
          		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
              //填充表头标题  
          	
          		int colSize = list.get(0).get(0).size(); 
              //合并单元格供标题使用(表名)  
              sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, colSize-1));  
              HSSFRow firstRow = sheet.createRow(0);//第几行（从0开始）  
              firstRow.setHeight((short)(800));
              HSSFCell firstCell = firstRow.createCell(0);  
              firstCell.setCellValue(title[0]);  
              firstCell.setCellStyle(style);  
              //合并单元格供第一个字符串使用  
              sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, colSize-1));  
              HSSFRow firstNextRow = sheet.createRow(1);//第几行（从0开始）  
              firstNextRow.setHeight((short)(500));
              HSSFCell firstNextCell = firstNextRow.createCell(0);  
              firstNextCell.setCellValue(strTitle);  
              firstNextCell.setCellStyle(style);  
            //合并单元格供第二个表格使用  
              sheet.addMergedRegion(new CellRangeAddress(list.get(0).size()+5, list.get(0).size()+5, 0, list.get(1).get(0).size()-1));  
              HSSFRow lastRow = sheet.createRow(list.get(0).size()+5);//第几行（从0开始）  
              lastRow.setHeight((short)(800));
              HSSFCell lastCell = lastRow.createCell(0);  
              lastCell.setCellValue(title[1]);  
              lastCell.setCellStyle(style); 
           
              //填充表头header  
            //countRow= 表名所占的一行1+标题行
              int countRow=2;
              for (int k = 0; k < headers.length; k++) {
 			  String [] header=headers[k];
 			  if(k==1)
 				 countRow=colSize;
               //填充表头header  
               HSSFRow row = sheet.createRow(countRow);  
               for(int i=0; i< header.length; i++) {  
             	  sheet.autoSizeColumn((short)i,true);
                   HSSFCell cell = row.createCell(i);  
                   cell.setCellValue(header[i]);  
                   cell.setCellStyle(style2);  
               }   
              //填充表格内容  
               List<List<Object>> contentList=list.get(k);
              int[] arr=new int[contentList.get(contentList.size()-1).size()];
              for(int i=0; i<contentList.size(); i++) { 
            	  countRow++;
                  HSSFRow row2 = sheet.createRow(countRow);//index：第几行  
                  List<?> rowList = contentList.get(i);  
                  int x=1;
                  for(int j=0; j<rowList.size(); j++) {
                	 int y=1;
                	 int r=1;
                	  String textValue = "";  
                      Object value = rowList.get(j);  
                      HSSFCell cell = row2.createCell(j);//第几列：从0开始  
                      if (value instanceof Integer) {
  						cell.setCellValue((Integer) value);
  					} else if (value instanceof Float) {
  						textValue = String.valueOf((Float) value);
  						cell.setCellValue(textValue);
  					} else if (value instanceof Double) {
  						textValue = String.valueOf((Double) value);
  						cell.setCellValue(textValue);
  					} else if (value instanceof Long) {
  						cell.setCellValue((Long) value);
  					} else if (value instanceof Boolean) {
  						textValue = "是";
  						if (!(Boolean) value) {
  							textValue = "否";
  						}
  						cell.setCellValue(textValue);
  					}else {
  						// 其它数据类型都当作字符串简单处理
  						if (value != null) {
  							textValue = value.toString();
  						}
  						cell.setCellValue(textValue);
  					}
                      cell.setCellStyle(style2); 
                      if(k==0){
                    	  //判断换行符
                    	  String[] str=textValue.split("\r\n");
                          for(int t= 0 ;t<str.length ;t++){
                        	  if(str[t].length()>r)
                        		  r=str[t].length();
                          }      
                          if(r>arr[j])
                        	  arr[j]=r;
                          y=textValue.split("\r\n").length;
                         if(y>x)
                        	 x=y;
                      }
                      
                  }  
                  if(k==0)
                	//设置表格行宽
                	  row2.setHeight((short)(x*300));
              }  
              if(k==0){
            	  //设置表格列宽
            	  for(int h=0;h<arr.length;h++){
                	  if("菜谱".equals(name)){
                	  sheet.setColumnWidth(h, 580*arr[h]);
                	  }else{
                		  if(h>0){
                			  sheet.setColumnWidth(h, 300*arr[h]);
                		  }else{
                			  sheet.setColumnWidth(h, 550*arr[h]);
                		  }
                	  }
                  }
                  if("菜谱".equals(name)){
                	  //合并表头单元格
                	  sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 2));   
                      sheet.addMergedRegion(new CellRangeAddress(2, 2, 3, 4)); 
                      sheet.addMergedRegion(new CellRangeAddress(2, 2, 5, 6)); 
                      sheet.addMergedRegion(new CellRangeAddress(2, 2, 7, 8)); 
                      sheet.addMergedRegion(new CellRangeAddress(2, 2, 9, 10));
                  }
              }
              
              }//表头for
        } catch(Exception ex) {  
            ex.printStackTrace();  
        }  
        return book;  
    } 
	/**
	 * 根据一周菜谱数据生成采购单Excel表格
	 */
	@Override
	public List< List< Object > > exportBuyExcel(PcMenuRecord pcMenuRecord){
		List< List< Object > > list=new ArrayList< >();
		List<HelpMenuDetail> helpList = findFoods(pcMenuRecord,true);
		String[] strDate={"星期一","星期二","星期三","星期四","星期五"};
		for(int i = 0 ; i< strDate.length ; i++){//星期几
			Map<String,BigDecimal> map=new HashMap<String,BigDecimal>();
			for(int j = 0 ; j< helpList.size() ; j++){//餐期
				Foods foods=helpList.get(j).getFoods().get(i);
				 List<PcFoodMaterial> material=foods.getMaterial();
				 if(material!=null){
					 for(PcFoodMaterial ma:material){
						 BigDecimal b=new BigDecimal(ma.getWeight());
						 if(map.containsKey(ma.getFodName())){
							 BigDecimal total=map.get(ma.getFodName());
							 total=total.add(b);
							 map.put(ma.getFodName(), total);
						 }else{
							 map.put(ma.getFodName(), b);
						 }
					 }
				 }
				 
			}
			Set<String> set=map.keySet();
			Iterator<String> it=set.iterator();
			List< Object >  temp = new ArrayList< >();
			int c=0;
			String str="";
			String name="";
			while(it.hasNext()){
				c++;
				 name=it.next();
				if(c%6==0){
					str+="\r\n"+name+":"+map.get(name).toString()+" kg   ";
				}else{
					str+=name+":"+map.get(name).toString()+" kg   ";
				}
			}
			temp.add(strDate[i]);
			temp.add(str);
			list.add(temp);
		}
		return list;
	}
	/**
	 * 生成菜谱表单+营养供给量表格数据集合
	 */
	@Override
	public List<List< List< Object > >> exportTwoExcel(PcMenuRecord pcMenuRecord){
		List<HelpMenuDetail> dlist = findFoods(pcMenuRecord,true);
		List< MenuFoods > dataList = new ArrayList<MenuFoods >();
		List<List< List< Object > > >list1=new ArrayList< List< List< Object > >>();
		for (HelpMenuDetail h:dlist){
			MenuFoods menuFoods=new MenuFoods();
			String meal=h.getMeal();
			List<String> fods=new ArrayList<String>();
			List<String> mas=new ArrayList<String>();
			List<Foods>  foods =h.getFoods();
			for(Foods f:foods){//包含星期一到星期五
				 List<PcMenuManage> food =f.getFood();
				 String fod=" ";
				 String ma=" ";
				 int n=0;
				for(PcMenuManage p:food){
					if(n==0)
						fod+=p.getMenName();
					else 
						fod+="\r\n"+p.getMenName();
				n++;
				}
				fods.add(fod);
				List<PcFoodMaterial> material=f.getMaterial();
				n=0;
				for(PcFoodMaterial m:material){
					if(n==0)
						ma+=m.getFodName()+":"+m.getWeight();
					else 
						ma+="\r\n"+m.getFodName()+":"+m.getWeight();
					n++;
				}
				mas.add(ma);
			}
			menuFoods.setMeal(meal);
			menuFoods.setFoods(fods);
			menuFoods.setMas(mas);
			dataList.add(menuFoods);
		}
		List< List< Object > > list=new ArrayList<List< Object > >();
		for (MenuFoods obj : dataList) {
			List< Object >  temp = new ArrayList<Object>();
			temp.add(obj.getMeal());
			temp.add(obj.getFoods().get(0));
			temp.add(obj.getMas().get(0));
			temp.add(obj.getFoods().get(1));
			temp.add(obj.getMas().get(1));
			temp.add(obj.getFoods().get(2));
			temp.add(obj.getMas().get(2));
			temp.add(obj.getFoods().get(3));
			temp.add(obj.getMas().get(3));
			temp.add(obj.getFoods().get(4));
			temp.add(obj.getMas().get(4));
			list.add(temp);
			}
		list1.add(list);
		List<Elements> eList=findElements(pcMenuRecord,dlist);
		List< List< Object > > list0=new ArrayList<List< Object > >();
		for (Elements obj : eList) {
			List< Object >  temp = new ArrayList<Object>();
			temp.add(obj.getTime());
			temp.add(obj.getEnergy());
			for(PcMicroElement ele:obj.getMiceList()){
				temp.add(ele.getMicAmount());
			}
			list0.add(temp);
		}
		list1.add(list0);
		return list1;
	}
 	
   	
}